using System;
using System.Collections.Generic;
using System.Threading;

namespace InfiniTec.Exchange.Notifications
{
	internal sealed class SubscriptionRestartStatus
	{
		public Dictionary<Subscription, Exception> Errors { get; private set; }

		public SubscriptionRestartStatus(int activeProcesses, int numberOfSubscriptions)
		{
			Errors = new Dictionary<Subscription, Exception>();
			_ActiveProcesses = activeProcesses;
			_NumberOfSubscriptions = numberOfSubscriptions;
		}

		private int _ActiveProcesses;
		private readonly int _NumberOfSubscriptions;
		private int _CompletedSubscriptions;
		private readonly object _ErrorsLock = new object();

		public bool CompleteRestartProcessor()
		{
			return Interlocked.Decrement(ref _ActiveProcesses) == 0;
		}

		public int CompleteSubscription()
		{
			return Interlocked.Increment(ref _CompletedSubscriptions)*100/_NumberOfSubscriptions;
		}

		public void RegisterFailedSubscription(Subscription subscription, Exception exception)
		{
			lock (_ErrorsLock)
			{
				Errors[subscription] = exception;
			}
		}
	}
}